package com.d3works.apps.base.rest.common;

import java.io.*;

/**
 * 资源处理工具类
 *
 * @author wang
 */
public class R {

  public static final String UTF_8 = "utf-8";

  /**
   * 桥接写入
   *
   * @param input
   * @param output
   * @throws IOException
   */
  public static void bridgeWrite(InputStream input, OutputStream output) throws IOException {
    bridgeWrite(input, output, true, true);
  }

  public static void bridgeWrite(
      InputStream input, OutputStream output, boolean closeIn, boolean closeOut)
      throws IOException {
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    int len = 0;
    while ((len = input.read(buffer)) > 0) {
      output.write(buffer, 0, len);
    }
    output.flush();
    if (closeIn) {
      input.close();
    }
    if (closeOut) {
      output.close();
    }
  }

  public static String readText(InputStream input, String charset, boolean closeSource)
      throws IOException {
    try {
      InputStreamReader reader = new InputStreamReader(input, charset);
      BufferedReader br = new BufferedReader(reader);
      StringBuffer sb = new StringBuffer();
      String tmp;
      while ((tmp = br.readLine()) != null) {
        sb.append(tmp).append("\n");
      }
      if (closeSource) {
        br.close();
      }
      input = null;
      return sb.toString();
    } finally {
      if (input != null) {
        try {
          input.close();
        } catch (Exception ex) {
        }
      }
    }
  }
}
